import adminApi from '@/services/adminApi';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import ShowRole from './components/ShowRole';
import UpdateRole from './components/UpdateRole';

export type TableListItem = API.roleTtem & Record<string, any>;

const User: React.FC = () => {
  const [showUpdateRole, setShowUpdateRole] = useState<number>(0);
  const [roleRow, setRoleRow] = useState<any>({});
  const [showRole, setShowRole] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '角色名称',
      dataIndex: 'name',
    },
    {
      title: '状态',
      width: 80,
      dataIndex: 'state',
      initialValue: 'all',
      valueEnum: {
        all: { text: '全部', status: 'Default' },
        true: { text: '启用', status: 'Processing' },
        false: { text: '禁用', status: 'Error' },
      },
    },
    {
      title: '备注',
      dataIndex: 'desc',
      ellipsis: true,
      copyable: true,
    },
    {
      title: '创建时间',
      width: 180,
      dataIndex: 'createdAt',
      valueType: 'dateTime',
      search: false,
      sorter: (a, b) => a.createdAt - b.createdAt,
    },
    {
      title: '更新时间',
      width: 180,
      dataIndex: 'updatedAt',
      valueType: 'dateTime',
      search: false,
      sorter: (a, b) => a.updatedAt - b.updatedAt,
    },
    {
      title: '操作',
      width: 180,
      key: 'option',
      valueType: 'option',
      render: (text, row: any, index, action) => [
        <a
          key="showRole"
          onClick={() => {
            setRoleRow(row);
            setShowRole(true);
          }}
        >
          查看
        </a>,
        <a
          key="editRole"
          onClick={() => {
            setRoleRow(row);
            setShowUpdateRole(2);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="popconfirm"
          title={`确认删除吗?`}
          okText="是"
          cancelText="否"
          onConfirm={async () => {
            const res = await adminApi.cwSys.AdminapiCwSysDelrole({ id: row.id });
            if (res.errorCode === '0') {
              action?.reload();
              message.success('删除成功');
            }
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <PageContainer
      extra={[
        <Button
          key="addRole"
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => setShowUpdateRole(1)}
        >
          添加角色
        </Button>,
      ]}
    >
      <ProTable
        actionRef={actionRef}
        columns={columns}
        request={async (params: any, sorter, filter): Promise<any> => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          console.log(params, sorter, filter);
          params.sorter = sorter;
          console.log(params);
          return await adminApi.cwSys.AdminapiCwSysRolelist(params);
        }}
        rowKey="id"
        pagination={{
          showQuickJumper: true,
        }}
        dateFormatter="string"
        headerTitle="角色列表"
      />
      <UpdateRole
        onCancel={() => {
          setShowUpdateRole(0);
        }}
        onSubmit={async (values: any) => {
          console.log(values);
          let res;
          if (showUpdateRole == 1) {
            res = await adminApi.cwSys.AdminapiCwSysAddrole({}, values);
          } else {
            res = await adminApi.cwSys.AdminapiCwSysEditrole({}, values);
          }
          if (res?.errorCode == '0') {
            setShowUpdateRole(0);
            actionRef?.current?.reload();
            message.success('操作成功！');
          }
        }}
        showUpdateRole={showUpdateRole}
        values={roleRow || {}}
      />
      <ShowRole id={roleRow.id} visible={showRole} onClose={() => setShowRole(false)} />
    </PageContainer>
  );
};
export default User;
